package com.spit.hkpost.mar

import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.gg.reader.api.dal.GClient
import com.gg.reader.api.protocol.gx.MsgAppGetBaseVersion
import com.gg.reader.api.protocol.gx.MsgBaseStop
import com.spit.hkpost.event.AppViewModel
import com.spit.hkpost.event.EventViewModel
import com.spit.hkpost.keyctrl.GlobalClient
import com.spit.hkpost.service.InitializeService
import com.spit.hkpost.service.PowerUtil
import com.tencent.mmkv.MMKV
import me.hgj.jetpackmvvm.base.BaseApp


//Application全局的ViewModel，里面存放了一些账户信息，基本配置信息等
val appViewModel: AppViewModel by lazy { MyApplication.appViewModelInstance }

//Application全局的ViewModel，用于发送全局通知操作
val eventViewModel: EventViewModel by lazy { MyApplication.eventViewModelInstance }

class MyApplication : BaseApp() {

    companion object {

        private lateinit var instance: MyApplication

        fun get(): MyApplication {
            return instance
        }

        lateinit var eventViewModelInstance: EventViewModel
        lateinit var appViewModelInstance: AppViewModel

    }

    override fun onCreate() {
        super.onCreate()
        MMKV.initialize(this)
        MMKV.defaultMMKV().sync()
        instance = this
        eventViewModelInstance = getAppViewModelProvider().get(EventViewModel::class.java)
        appViewModelInstance = getAppViewModelProvider().get(AppViewModel::class.java)
        InitializeService.start(this)

        PowerUtil.power("1")
        init()
    }

    private fun init() {
        val baudRateList = intArrayOf(460800, 115200)
        for (i in baudRateList) {
            val b: Boolean = openReader(i.toString() + "")
            if (b) {
                break
            }
        }
    }

    var client: GClient = GlobalClient.getClient()
    private fun openReader(baudRate: String): Boolean {
        if (client.openAndroidSerial("/dev/ttyS3:$baudRate", 0)) {
            val stop = MsgBaseStop()
            client.sendSynMsg(stop)
            if (stop.rtCode == 0.toByte()) {
                val getBaseVersion = MsgAppGetBaseVersion()
                client.sendSynMsg(getBaseVersion)
                LogUtils.e(
                    "RFID模块连接成功",
                    getBaseVersion.baseVersions
                )
                return true
            } else {
                client.close()
                return false
            }
        } else {
            ToastUtils.showShort("識別串口失敗，請重新打開APP")
        }
        return false
    }
}
